#include "header.h"

static int 		np, myid;
static int 	        flag = 1;
static MPI_Status       status;
static char 		line[80];
static ptrdiff_t	alloc_local;

void arr3d_init(ctrl_ptr in, work_ptr work)
{
  FILE			*fhlog;
  int			n, n0, n1, n2;
  n = in->n; n0 = n; n1 = n; n2 = n;	  
  fftw_plan		test_plan;
  
  MPI_Comm_size(COMM, &np);
  MPI_Comm_rank(COMM, &myid);

  MPI_Barrier(COMM);  
  fftw_mpi_init();
  alloc_local = fftw_mpi_local_size_3d(n, n, n, COMM, &(work->l_n0), &(work->l_0_start));
  work->wrk  = fftw_alloc_complex(alloc_local);
  work->ft   = fftw_alloc_complex(alloc_local);
  work->grv  = fftw_alloc_complex(alloc_local);
  //work->grv2  = fftw_alloc_complex(alloc_local);
  work->tmp  = fftw_alloc_complex(alloc_local);
  //printf("Making a test plan\n");
  //MPI_Barrier(COMM);
  //test_plan  = fftw_mpi_plan_dft_3d(n,n,n,work->wrk,work->ft, COMM, FFTW_FORWARD, FMODE);
  //MPI_Barrier(COMM);
  //printf("Test plan succeeded.\n");
  //printf("Id %d allocates %td fftw_complexes. Local n0 %td,starting at %td\n", myid, alloc_local, work->l_n0, work->l_0_start );
  work->alloc_local = alloc_local;
  sprintf(line,"%s.log",in->runname);
  MPI_Barrier(COMM);
  if (myid == 0) fhlog = fopen(line,"a");
  if (myid != 0) {
    MPI_Recv(&flag, 1, INT, myid-1, myid, COMM, &status);
    fhlog = fopen(line,"a");
  }
  
  fprintf(fhlog,"proccess %d to allocate %f MBs\n",myid, (work->alloc_local)/pow(2.,20));

  if (work->wrk == NULL) fprintf(fhlog,"proccess %d failed to allocate.\n",myid);
  if (work->ft  == NULL) fprintf(fhlog,"proccess %d failed to allocate.\n",myid);
  if (work->grv == NULL) fprintf(fhlog,"proccess %d failed to allocate.\n",myid);
  if (work->tmp == NULL) fprintf(fhlog,"proccess %d failed to allocate.\n",myid);
  fclose(fhlog);

  if (myid != np-1) MPI_Send(&flag, 1, INT, myid+1, myid+1, COMM);
}
